package cn.helper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.icu.util.Calendar;
import android.icu.util.GregorianCalendar;
import android.icu.util.TimeZone;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.unity3d.player.UnityPlayer;

import java.io.File;
import java.util.UUID;

public class SystemHelper {

    private final static String Tag = "BToolkit";

    /**
     * 当前设备 Android API 版本号(返回API版本号 29,30等)
     *
     * @return
     */
    public static int getAndroidSDKVersion() {
        Log.i(Tag, "getDeviceAPIVersion(): Build.VERSION.SDK_INT: " + Build.VERSION.SDK_INT);
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取电量
     * <uses-permission android:name="android.permission.BATTERY_STATS" />
     */
    @SuppressLint("NewApi")
    public static int getBatteryPercent() {
        int currentApiVersion = Build.VERSION.SDK_INT;
        if (currentApiVersion >= 21) {
            // 仅支持Andorid-21及以上版本
            BatteryManager batteryManager = (BatteryManager) UnityPlayer.currentActivity.getSystemService(Context.BATTERY_SERVICE);
            int percent = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);// 整数百分比（0-100）
            return percent;
        }
        return 0;
    }

    /**
     * 获取网络类型
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     */
    public static String getInternetType() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) UnityPlayer.currentActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
            int type = mNetworkInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                return "Wifi";
            } else {
                return "Mobile";
            }
        }
        return "NoNet";
    }

    // 判断是否存在光传感器来判断是否为模拟器
    public static boolean isSimulator() {
        SensorManager sensorManager = (SensorManager) UnityPlayer.currentActivity.getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); // 光传感器
        if (null == sensor) {
            return true;
        } else {
            return false;
        }
    }

    // 无需权限获取唯一UUID识别码
    public static String getDeviceID() {
        String serial = "serial";
        String m_szDevIDShort = "LT" + Build.BOARD + Build.BRAND + Build.DEVICE + Build.MANUFACTURER + Build.PRODUCT;
        //使用硬件信息拼凑出来的号码
        String s = new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        return s;
    }

    // 获取系统时区ID（如：Asia/Shanghai）
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String getSysTimeZoneID() {
        TimeZone timeZone = TimeZone.getDefault();
        return timeZone.getID();
    }

    // 获取系统时区Name（如：GMT+08:00）
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String getSysTimeZoneName() {
        TimeZone tz = TimeZone.getDefault();
        Calendar cal = GregorianCalendar.getInstance(tz);
        int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
        String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
        return "GMT" + (offsetInMillis >= 0 ? "+" : "-") + offset;
    }

    /**
     * 安装Apk（三步）
     * 1、配置权限<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
     * 2、配置provider
     * <provider
     *     android:name="android.support.v4.content.FileProvider"
     *     android:authorities="${applicationId}.fileProvider"
     *     android:exported="false"
     *     android:grantUriPermissions="true">
     *     <meta-data
     *     	android:name="android.support.FILE_PROVIDER_PATHS"
     *         android:resource="@xml/provider_paths" />
     * </provider>
     * 3、创建xml文件配置一次性临时存储位置，并把xml文件名赋值给provider,然后该xml导出aar包给Unity使用（provider_xml.aar已导出到Unity目录）
     * 教程：https://blog.csdn.net/lanlangaogao/article/details/125291127
     */
    public static void installApk(String path) {
        File file = new File(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Activity context = UnityPlayer.currentActivity;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //注意第二个参数，要保持和manifest中android:authorities的值相同
            Uri uri = FileProvider.getUriForFile(context,context.getPackageName() + ".fileProvider", file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}